const express = require('express');
const sqlite3 = require('sqlite3');

const router = express.Router();

const db = new sqlite3.Database("/home/john/source/adc/db/adc2.db");//,sqlite3.OPEN_READONLY)

//返回一天的温度数据
router.post('/temp',function(req,res){
    let {n} = req.body;
    console.log("temp:"+n);
    db.all(`select * from tempadc order by id desc limit ${n}`,[],(err,rows)=>{
        if(err){
            res.json({'err':err.message,data:null});
        }else{
            res.json({'err':null,data:rows.reverse()});
        }
    })
});

//返回最近n天的温度数据
//例如：n=0返回最近一天的温度数据
//n=1返回昨天的全部数据
//n=2返回前天的全部数据
router.post('/temp_nday',function(req,res){
    let {n} = req.body;
    let now = new Date();
    let ei = now.getTime()-n*24*60*60*1000;
    let bi = now.getTime()-(n-1)*24*60*60*1000;
    console.log("temp_nday:"+n);
    db.all(`select * from tempadc where time>${bi} and time<${ei}`,[],(err,rows)=>{
        if(err){
            res.json({'err':err.message,data:null});
        }else{
            res.json({'err':null,data:rows.reverse()});
        }
    })
});

module.exports =  router;
